#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
use File::Basename;
use Getopt::Long;
use Pod::Usage;

my $backup_type=undef;          # Type of Backup to be run (LOG or DB)
my $backup_sid=undef;           # SID of Database
my $generation=undef;           # Flag for generation backups
my $autolog=undef;                      # Flag for logbackups done via autolog into filesystem
my $flag_help;                          # Help Flag


GetOptions("type=s"=>\$backup_type,
                   "sid=s"=>\$backup_sid,
                   "generation"=>\$generation,
                   "autolog"=>\$autolog,
                   "help|?"=>\$flag_help);

&pod2usage(verbose=>2) if ($flag_help); # display usage info if help flag is defined
&pod2usage(verbose=>0,message=>"please supply backup type and SID") unless ($backup_type or $backup_sid); # display usage info if options are missing

my $nsr_path = ( $^O =~ m/Win/) ? 'C:/Legato/nsr' : '/nsr'; # setting networker path depending on OS
my $config_file= $nsr_path.'/res/nsrMaxDB_'.$backup_sid.'.cfg'; # setting config-file to use
my @pass;

my %options=(
                                nr_ignores=>1, # times to ignore LOG run while db backup is running - default is 1 max is 3
                                nr_ignores_force=>'', # force parameter to increase nr_ignores up to a max of 12
                                nr_wait=>2, # wait x * 5min , max. 1 hours - default is 10 minutes - time to wait db backup for running log backup
                                user=>'', # user for connection to database
                                pwd=>'', # password for user
                                dbmcli_bin=>'', # path of dbmcli
                                nsr_env_path=> $nsr_path.'/res', # environment files path
                                maxdb_env=> $nsr_path.'/res/env_'.$backup_sid, # environment file for maxdb
                                maxdb_env_backup=> $nsr_path.'/res/env_'.$backup_type.'_'.$backup_sid, # environment template file for db backup
                                maxdb_env_backup_generation=> $nsr_path.'/res/env_'.$backup_type.'_'.$backup_sid.'_Generation', # environment template file for db-generation backup
                                nsr_log_file=> $nsr_path.'/logs/test_'.$backup_sid.'.log', # networker logfile
                                lck_log_file=> $nsr_path.'/tmp/LOG_'.$backup_sid.'_run.lck',  # lock file for log backup
                                lck_db_file=> $nsr_path.'/tmp/DB_'.$backup_sid.'_run.lck',  # lock file for db backup
                                lck_run_file=> $nsr_path.'/tmp/LOG_'.$backup_sid.'_runs_check.lck', # lock file for log backup counter
                                lck_backup_file=> $nsr_path.'/tmp/'.$backup_type.'_'.$backup_sid.'_run.lck', # lock file for defined backup_type
                                error_nr=>2, # error-code to be returned - default is higher than 0
                                NSR_ENV=>undef,
                                NSR_MAST=>undef,
                                nr_backup_medium=>1

);


############################### SUB's ###############################

# sub for reading of configured parameters in config file; paths are mandatory, retentions are optional
sub read_parameter_file(){

my $read_parameter_file=0; # set default return value for sub
open(PARAMETER_FILE,"<$config_file") or die "could not open parameterfile $config_file: $!"; # open config file
        my @parameters=<PARAMETER_FILE>; # read paramters from configfile
        chomp @parameters; # cut \n
close(PARAMETER_FILE); # close file

foreach (@parameters){ # read each line in config file
        next if ($_ =~ m/^$/ || $_ =~ m/^#/); # skip empty line or line begin with # = comment
        my($key,$value)=split(/\s*=\s*/,$_,2); # split line into key and value, from form key = value
        if ($key ne "pwd"){$value=~ s/\s*#.*//g if ($value =~ m/#/);} # check if line contains comment # - and cut comment only if line does not contain password
        $options{$key}=$value; # set key and value in hash
}
if ((not -e $options{dbmcli_bin}) or (not $options{user}) or (not $options{pwd})){
        &logging ("faulty/missing entries in cfg-file - please check");$options{error_nr} = 5;
        &logging ("-" x 40); # logfile entry spacer line
        exit $options{error_nr} # exit with predefined error_nr 2
}
@pass=unpack("C*",$options{pwd});
foreach (@pass){$_--;}
return $read_parameter_file; # return sub status 0 = ok, 1 = not ok (abort flag)
}

# sub for message logging - messages are print to command line and log file
sub logging {
 my $log_message = join(' ',@_);
 open (LOG,">>$options{nsr_log_file}") or die "could not open log file $options{nsr_log_file}\n"; # open log-file
 print localtime()." ".$log_message."\n";       # print message with timestamp onto STDOUT (into commandline for manual started backups)
 print LOG localtime()." ".$log_message."\n"; # print message with timestamp into log-file
 close (LOG) or die "could not close log file $options{nsr_log_file}\n"; # close log-file
}


############################## MAIN ###############################

&logging ("-" x 40); # logfile entry spacer line

read_parameter_file(); # read entries from parameter file
my $strg=pack("C*",@pass);
$options{pwd}=reverse(substr(lcfirst($strg),0,length($strg)/2)).lcfirst(reverse(substr($strg,length($strg)/2)));
my $maxdb_usr_connect = "-u $options{user},$options{pwd}"; # connection string user,password
my $maxdb_util_connect = "-uUTL $options{user},$options{pwd}"; # connection string utility session user,password

umask 0111; # setting umask thus file permission is 666
my $db_connection = "$maxdb_usr_connect $maxdb_util_connect"; # putting together whole connection string
my $maxdb_conf_check_command= "$options{dbmcli_bin} -d $backup_sid $db_connection dbm_configget";


my @dbm_config=`$maxdb_conf_check_command`;

chomp @dbm_config;

foreach (@dbm_config){
        next if ($_ =~ m/^$/ || $_ =~ m/^OK/);
        my ($key,$value)=split(/\s*=\s*/,$_,2);
        $options{$key}=$value;

}
print "$options{NSR_ENV}\n";
print "$options{maxdb_env}\n";

if ((not $options{NSR_ENV}) || (not $options{NSR_ENV}=~ /\b$options{maxdb_env}\b/)){
       &logging("nsr_env passt nicht");
        &logging("NSR_ENV = $options{NSR_ENV}");
        &logging(`$options{dbmcli_bin} -d $backup_sid $db_connection dbm_configset -raw NSR_ENV $options{maxdb_env}`);
}
if ((not $options{NSR_MAST}) || (not $options{NSR_MAST}=~ /\bnsradmin\b/)){
        &logging("nsrmast nicht gesetzt");
       &logging(`$options{dbmcli_bin} -d $backup_sid $db_connection dbm_configset -raw set_variable_1 NSR_MAST=nsradmin`);
}


my @medium=`$options{dbmcli_bin} -d $backup_sid $db_connection medium_getall`;
chomp @medium;
my @med;
my $pipe;
my $command;
foreach (@medium){
next if (not($_ =~ /^NSR_*/));
print "$_\n";
my ($key,$value)=split(/\s*\/\s*/,$_,2);
print "$key\n";
push (@med,$key);
}

foreach (@med){
&logging(`$options{dbmcli_bin} -d $backup_sid $db_connection medium_delete $_`);
}

my @devs=`$options{dbmcli_bin} -d $backup_sid $db_connection param_directget MAXBACKUPDEVS`;
print "devs ---    @devs\n";
foreach (@devs){
next if (not $_ =~ /^MAX/);
print "$_\n";
my ($key,$value)=split(/\t/,$_,2);
&logging("Number of devices= $value");
&logging("number of devs in cfg= $options{nr_backup_medium}");
if ($value>$options{nr_backup_medium}){&logging("check config -> too many devs wanted");exit "check config -> too many devs wanted";}
}
if (not ($nsr_path =~ m/^\/nsr/)){$pipe='\\\\.\\pipe\\';} else {$pipe='/nsr/pipe/';}
my $i=1;
while ($i<=$options{nr_backup_medium}){
if ($i==$options{nr_backup_medium}){$command="$options{dbmcli_bin} -d $backup_sid $db_connection medium_put NSR_DB_$backup_sid $pipe"."pipe1_DB_$backup_sid".' PIPE DATA 0 8 NO NO "" NSR';}
$command="$options{dbmcli_bin} -d $backup_sid $db_connection medium_put NSR_DB_$backup_sid"."\\\\P0"."$i $pipe"."pipe"."$i"."_DB_$backup_sid".' PIPE DATA 0 8 NO NO "" NSR';
print "$command\n";
&logging(`$command`);
$i++;
}
my $log_pipe_command="$options{dbmcli_bin} -d $backup_sid $db_connection medium_put NSR_LOG_$backup_sid $pipe"."pipe1_LOG_$backup_sid".' PIPE LOG 0 8 NO NO "" NSR';
&logging(`$log_pipe_command`);
&logging(`$options{dbmcli_bin} -d $backup_sid $db_connection medium_getall`);

